#include "app_msg.h"

gate_state_t json_2_msg(char *json, msg_t *msg)
{
    if (json == NULL || msg == NULL)
    {
        log_error("json_2_msg: json or msg is null");
        return GATE_ERROR;
    }

    cJSON *root = cJSON_Parse(json);
    if (root == NULL)
    {
        log_error("json_2_msg: parse json error");
        return GATE_ERROR;
    }

    msg->connetType = strdup(cJSON_GetObjectItem(root, "connType")->valuestring);
    msg->action = strdup(cJSON_GetObjectItem(root, "action")->valuestring);
    msg->motorId = cJSON_GetObjectItem(root, "motorId")->valueint;

    cJSON *motorSpeedItem = cJSON_GetObjectItem(root, "motorSpeed");
    if (motorSpeedItem != NULL)
    {
        msg->motorSpeed = motorSpeedItem->valueint;
    }

    cJSON *statusItem = cJSON_GetObjectItem(root, "status");
    if (statusItem != NULL)
    {
        msg->status = strdup(statusItem->valuestring);
    }
    cJSON_Delete(root);

    return GATE_OK;
}

gate_state_t msg_2_json(msg_t *msg, char json[])
{
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "action", msg->action);
    cJSON_AddStringToObject(root, "connType", msg->connetType);
    cJSON_AddNumberToObject(root, "motorId", msg->motorId);
    cJSON_AddNumberToObject(root, "motorSpeed", msg->motorSpeed);

    if (msg->status != NULL)
    {
        cJSON_AddStringToObject(root, "status", msg->status);
    }

    char *str = cJSON_PrintUnformatted(root);
    strcpy(json, str);
    json[strlen(str)] = '\0';

    cJSON_Delete(root);

    return GATE_OK;
}
